import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import './index.css';



const Cell = function (props) {
  return (
    <div className="cell" onClick={props.onClick}>{props.text}</div>
  )
}

const ChessBorad = function () {
  let [n, setN] = useState(0)
  const [finished, setFinished] = useState(false)
  const [winner, setWinner] = useState('')

  const [cells, setCells] = useState([
    [null, null, null],
    [null, null, null],
    [null, null, null],
  ])


  const win = function (cells) {

    for (let i = 0; i < 3; i++) {
      if (cells[i][0] === cells[i][1] && cells[i][1] === cells[i][2] && cells[i][0] !== null) {
        setWinner(cells[i][0])
        setFinished(true)
      }
    }

    for (let i = 0; i < 3; i++) {
      if (cells[0][i] === cells[1][i] && cells[1][i] === cells[2][i] && cells[0][i] !== null) {
        setWinner(cells[0][i])
        setFinished(true)
      }
    }

    if (cells[0][0] === cells[1][1] && cells[1][1] === cells[2][2] && cells[0][0] !== null) {
      setWinner(cells[0][0])
      setFinished(true)
    }
    if (cells[0][2] === cells[1][1] && cells[1][1] === cells[2][0] && cells[0][2] !== null) {
      setWinner(cells[0][2])
      setFinished(true)
    }
  }

  const onClickCell = function (row, col) {
    if(cells[row][col] !== null){
      console.log('不能在已经有标记的地方下')
      return
    }

    if (finished || n === 9) {
      return
    }
    cells[row][col] = n % 2 === 0 ? 'x' : 'o'
    const copy = JSON.parse(JSON.stringify(cells))
    setCells(copy)
    setN(n + 1)

    win(copy)
  }

  return (
    <div>
      <div>第{n}手</div>
      {cells.map((items, row) => <div className="row">
        {items.map((item, col) => <Cell onClick={() => onClickCell(row, col)} text={item} />)}
      </div>)}
      {finished && <div>游戏结束,{winner}赢了</div>}
      {!finished && n === 9 && <div>游戏结束,平局</div>}
    </div>
  )
}




ReactDOM.render(
  <ChessBorad />,
  document.getElementById('root')
);

